import re
import requests
import execjs
import time
import JsCode
import random


class QuestionA:
    def __init__(self, id, source, ua):
        """
        :param id:要填写的问卷的id
        """
        self.__id = id
        self.__source = source
        self.__post_url = None
        self.__data = None
        self.__headers = None
        self.__ua = ua
        self.__js_engine = execjs.compile(JsCode.JSCODE)

    def __get_jqparam(self, random, time):
        return self.__js_engine.call('jamieDe', random, time, self.__id)

    def __set_header(self):
        self.__headers = {
            'Content-Type': 'application/x-www-form-urlencoded',
            'Referer': 'https://www.wjx.cn/jq/' + str(id) + '.aspx',
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.105 Safari/537.36',
            # 'Sec-Fetch-Dest': 'document',
            # 'Sec-Fetch-Mode': 'navigate',
            # 'Sec-Fetch-Site': 'none',
            # 'Sec-Fetch-User': '?1',
            # 'Upgrade-Insecure-Requests': '1',
            'Cookie': '.ASPXANONYMOUS=jUMdnToF1wEkAAAAMzMyOTA4ZjEtNWNmYi00MTM5LWJlYjYtMGVmNzA2ZTFkNzZkdcCCvFw8LZp6S9K0Y4fn-dk5FFI1; spiderregkey=google.com%c2%a7%e7%9b%b4%e8%be%be%c2%a71; u_asec='+self.__ua+'; jac96589289=83861631; jac100290233=71933590; SERVERID=3f9180de4977a2b2031e23b89d53baa6|1607659438|1607658450'
        }

    def __get_ktimes(self):
        """
        随机生成一个ktimes,ktimes是构造post_url需要的参数，为一个整数
        :return:
        """
        return 39
        return random.randint(100, 200)

    def __get_jqnonce(self):
        """
        通过正则表达式找出jqnonce,jqnonce是构造post_url需要的参数
        :param response: 访问问卷网页，返回的reaponse
        :return: 找到的jqnonce
        """

        jqnonce = re.search(r'.{8}-.{4}-.{4}-.{4}-.{12}', self.__source)
        return jqnonce.group()

    def __get_rn(self):
        """
        通过正则表达式找出rn,rn是构造post_url需要的参数
        :param response: 访问问卷网页，返回的reaponse
        :return: 找到的rn
        """
        rn = re.search(r'\d{9,10}\.\d{8}', self.__source)
        return rn.group()

    def __get_jqsign(self, ktimes, jqnonce):
        """
        通过ktimes和jqnonce计算jqsign,jqsign是构造post_url需要的参数
        :param ktimes: ktimes
        :param jqnonce: jqnonce
        :return: 生成的jqsign
        """
        result = []
        b = ktimes % 10
        if b == 0:
            b = 1
        for char in list(jqnonce):
            f = ord(char) ^ b
            result.append(chr(f))
        return ''.join(result)

    def __get_start_time(self):
        """
        通过正则表达式找出问卷starttime,问卷是构造post_url需要的参数
        :param response: 访问问卷网页，返回的reaponse
        :return: 找到的starttime
        """
        start_time = re.search(r'\d+?/\d+?/\d+?\s\d+?:\d{2}', self.__source)
        return start_time.group()

    def __generate_post_url(self):
        """
        生成post_url
        :return:
        """
        self.__set_header()  # 设置请求头，更换ip

        ktimes = self.__get_ktimes()  # 获取ktimes

        jqnonce = self.__get_jqnonce()  # 获取jqnonce

        rn = self.__get_rn()  # 获取rn

        jqsign = self.__get_jqsign(ktimes, jqnonce)  # 生成jqsign

        start_time = self.__get_start_time()+":0"+str(random.randint(0, 3))  # 获取starttime

        jqpram = self.__get_jqparam(rn[:rn.find('.')], start_time)  # 获取jqparam

        time_stamp = '{}{}'.format(
            int(time.time()), random.randint(100, 200))  # 生成一个时间戳，最后三位为随机数

        url = 'https://www.wjx.cn/joinnew/processjq.ashx?submittype=1&source=directphone&curID={}&t={}&starttim' \
              'e={}&ktimes={}&rn={}&hlv=1&jqnonce={}&jqsign={}&jqpram={}&u_asec={}&u_atype=2'.format(
                  self.__id, time_stamp, start_time, ktimes, rn, jqnonce, jqsign, jqpram, self.__ua)

        self.__post_url = url  # 设置url

    def __exec(self):
        """
        发送数据给服务器
        :return: 服务器返回的结果
        """
        print("url: " + self.__post_url)
        print()
        print("data: " + self.__data)
        # print()
        # print("header: " + self.__headers)

        requests.packages.urllib3.disable_warnings()  # 屏蔽错误
        response = requests.post(
            url=self.__post_url, data=self.__data, headers=self.__headers, verify=False)
        return response.text

    def run(self):
        """
        填写一次问卷
        :return:
        """
        self.__generate_post_url()
        print(self.__exec())

    def mul_run(self, data, num):
        """
        填写多次问卷
        :return:
        """
        self.__data = 'submitdata='+data
        for i in range(num):
            time.sleep(10)
            self.run()
            print('=========================第%d份提交完成========================' % i)
            time.sleep(random.randint(5, 10))   # 等待一会再提交，减少出验证码的概率
